<template>
    <div class="e-form">
        <BillTop  @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="摊销明细"
                    name="detailed"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="分包商摊销成本"
                    name="cost"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="附件信息"
                    name="attach"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form
                                :model="basicForm"
                                :label-width="formLabelWidth"
                                   ref="ruleForm"
                             :rules="rules"
                             class="demo-ruleForm"
                            >
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="摊销编号：">
                                            <span>{{ basicForm.billNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="机构：">
                                            <span>{{ basicForm.orgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row>
                                    <el-col :span="12">
                                         <el-form-item label="摊销日期：" v-if="isRedSingle">
                                            <span>
                                                {{
                                                    basicForm.amortizationDate
                                                }}
                                            </span>
                                        </el-form-item>
                                        <el-form-item label="摊销日期：" prop="amortizationDate" v-else>
                                             <el-date-picker
                                            value-format="yyyy-MM-dd"
                                            :clearable="false"
                                            type="date"
                                            placeholder="选择日期"
                                            v-model="basicForm.amortizationDate"
                                        ></el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="录入人：">
                                            <span>
                                                {{ basicForm.inputName }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="摊销金额（元）：">
                                            <span>
                                                {{
                                                    basicForm.amortizationAmount
                                                }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="报销数量：">
                                            <span>
                                                {{
                                                    basicForm.amortizationQuantity
                                                }}
                                            </span>
                                        </el-form-item>
                                    </el-col>

                                </el-row>
                                <el-row>
                                     <el-col :span="12">
                                          <el-form-item label="币种：" v-if="isRedSingle">
                                            <span>
                                                {{
                                                    basicForm.currency
                                                }}
                                            </span>
                                        </el-form-item>
                                <el-form-item label="币种：" prop="currencyId" v-else>
                                     <el-select

                                v-model="basicForm.currencyId"
                                placeholder="请选择"
                                @change="currencyChange"
                            >
                                <el-option
                                    v-for="(
                                        item
                                    ) in currencyForm"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                >
                                </el-option>
                            </el-select>
                                </el-form-item>
                            </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="人民币汇率：">
                                            <span>{{ basicForm.rmbRate }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="本位币：">
                                            <span>{{
                                                basicForm.baseCurName
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                      <el-col :span="12">
                                        <el-form-item
                                            label="本位币汇率："
                                            v-if="showBaseCurName"
                                        >
                                         <span v-if="isRedSingle">
                                                {{
                                                  basicForm.baseCurRate
                                                }}
                                            </span>
                                            <el-input
                                               v-else
                                                v-model="basicForm.baseCurRate"
                                            ></el-input>

                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="备注：">
                                            <el-input
                                                type="textarea"
                                                v-model="basicForm.remarks"
                                                autocomplete="off"
                                            ></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>

                                    <el-col :span="12">
                                        <el-form-item label="传财务共享：">
                                        </el-form-item>
                                    </el-col>
                                      <el-col :span="12">
                                        <el-form-item label="状态：">
                                            <span>
                                                {{  statusLable(basicForm.state)  }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                    <el-row>
                        <el-form-item label="冲红单" v-if="isRedSingle"
                            ><span :style="redBillStateStyle">{{
                                redBillStateFun
                            }}</span></el-form-item
                        >
                    </el-row>
                            </el-form>
                        </div>
                    </div>
                    <!-- 摊销明细 -->
                    <div id="detailedCon" class="con">
                        <div class="tabs-title" id="detailed">摊销明细</div>
                        <div class="e-table">
                            <div class="top"  v-if="!isRedSingle">
                                <div class="left">
                                    <el-button size="mini" type="primary"
                                        @click="clickMoneySource"
                                        >选择摊销金额物资</el-button
                                    >
                                    <el-button size="mini" type="primary"
                                        @click="clickNumSource"
                                        >选择数量摊销物资</el-button
                                    >
                                </div>
                            </div>
                               <el-table
                                class="table"
                                :data="detailedTableDataComputed"
                                border
                                style="width: 100%"
                                 default-expand-all
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                ref="multipleTable"
                                row-key="uuid"
                                 :row-class-name="tableRowClassName"
                                 :max-height="$store.state.tableHeight"
                                 v-sortTable="{ 'tableData': detailedTableDataComputed, '_this': this, 'ref': 'multipleTable' }"
                            >
                                <el-table-column
                                    label="操作"
                                    fixed
                                    width="100px"
                                    align="left"
                                >

                                    <template slot-scope="{ row, $index }">

                                        <i
                                            class="el-icon-delete"
                                            style="
                                                cursor: pointer;
                                                font-size: 20px;
                                                color: red;
                                            "
                                            :class="{
                                                'icon-delete-active-color':
                                                    MouseEnterId == row.dtlId
                                            }"
                                            @click="deleteEle(row,$index)"
                                            v-if="$index > 0&&!isRedSingle"
                                        ></i>

                                    </template>

                                </el-table-column>
                                <el-table-column
                                    prop="materialClassName"
                                    label="类别"
                                    mini-width="300"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialName"
                                    label="物资名称"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="spec"
                                    label="规格"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="计量单位"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="texture"
                                    label="材质"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="quantity"
                                    label="原数量"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="amount"
                                    label="原金额"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="currAmortizationQuantity"
                                    label="本次报销数量"
                                    width="200"
                                >
                                   <template slot-scope="{row,$index}">
                                    <el-input v-if="$index>0&&(row.amortizationType===1||row.amortizationType===2)" v-model="row.currAmortizationQuantity" @input="curStateChange(row)"></el-input>
                                </template>
                                </el-table-column>
                                  <el-table-column
                                    v-if="isRedSingle"
                                    prop="currAmortizationAmount"
                                    label="本次摊销金额（元）"
                                    width="200"
                                >

                                </el-table-column>
                                <el-table-column
                                    prop="currAmortizationAmount"
                                    label="本次摊销金额（元）"
                                    width="200"
                                >
                                <template slot-scope="{row,$index}">

                                    <el-input v-if="$index>0&&row.amortizationType===0" v-model="row.currAmortizationAmount" @input="curStateChange(row)"></el-input>
                                </template>
                                </el-table-column>
                                <el-table-column
                                    prop="prevTotalAmortizationQuantity"
                                    label="截止上期末已摊销数量"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="prevTotalAmortizationAmount"
                                    label="截止上期末已摊销金额"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="currTotalAmortizationQuantity"
                                    label="截止本期末已摊销数量"
                                    width="200"
                                >
                                    <template slot-scope="{row,$index}">
                                        <span v-if="$index>0">
                                            {{
                                                row.currTotalAmortizationQuantity
                                            }}
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="currTotalAmortizationAmount"
                                    label="截止本期末已摊销金额（元）"
                                    width="200"
                                    style="color: red"
                                >
                                  <template slot-scope="{row,$index}">
                                        <span v-if="$index>0">
                                            {{
                                                row.currTotalAmortizationAmount
                                            }}
                                        </span>
                                    </template>
                                </el-table-column>
                            </el-table>

                        </div>
                    </div>
                    <!-- 摊销成本 -->
                    <div id="costCon" class="con">
                        <div class="tabs-title" id="cost">摊销成本</div>

                            <div class="e-table">
                                   <div class="top" v-if="!isRedSingle">
                                <div class="left">
                                    <el-button size="mini" type="primary"

                                        @click="amortizationReturnSelectContract"
                                        >选择分包商</el-button

                                    >
                                </div>
                            </div>
                                <el-table
                                :data="costTableData"
                                 class="table"
                                border
                                style="width: 100%"
                                ref="detailed"
                                :row-class-name="tableRowClassName"
                                 v-sortTable="{ 'tableData': costTableData, '_this': this, 'ref': 'detailed' }"
                                >
                                <el-table-column fixed label="操作" width="70">
                                    <template slot-scope="{ row}">
                                        <div class="handle">
                                            <div style=" cursor: pointer;">
                                                <img src="@/assets/btn/delete.png"  @click="handleTurnoverDelete(row)">
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                  <el-table-column
                                    prop="subcontractorName"
                                    label="外包方名称"
                                    mini-width="300"
                                >
                                </el-table-column>
                                  <el-table-column
                                    prop="subcontractName"
                                    label="合同名称"
                                    mini-width="300"
                                >
                                </el-table-column>
                                  <el-table-column
                                    prop="subcontractNumber"
                                    label="合同编号"
                                    mini-width="300"
                                >
                                </el-table-column>
                                  <el-table-column
                                    prop="planAmount"
                                    label="设计金额"
                                    mini-width="300"
                                >
                                </el-table-column>
                                  <el-table-column
                                    prop="apportionmentRatio"
                                    label="分摊比例%"
                                    mini-width="300"
                                >
                                </el-table-column>
                                  <el-table-column
                                    prop="apportionmentAmount"
                                    label="分摊金额"
                                    mini-width="300"
                                >
                                <template slot-scope="{row}">
                                    <el-input @input="curStateChange(row)" v-model="row.apportionmentAmount"
                                     v-enter-float="{
                                                set: row,
                                                key:'apportionmentAmount'
                                            }"
                                    ></el-input>
                                </template>
                                </el-table-column>
                                  <el-table-column
                                    prop="providType"
                                    label="甲供类型"
                                    mini-width="300"
                                >
                                <template slot-scope="{row}">
                                    <el-select v-if="row.subcontractType==1||row.subcontractType==2" v-model="row.providType"
                                     @change="curStateChange(row)"
                                    >
                                        <el-option v-for="item in  providTypeArr" :key="item.value"
                                        :value="item.value"
                                        :label="item.label"
                                        ></el-option>
                                    </el-select>
                                    <span v-if="row.subcontractType==3" >销售消耗</span>

                                </template>
                                </el-table-column>
                                  <el-table-column
                                    prop="consumeType"
                                    label="消耗类型"
                                    mini-width="300"
                                >
                            <template slot-scope="{row}">
                                      <span v-if="row.subcontractType==1">{{consumeTypeComputed(row)}}</span>
                                      <span v-if="row.subcontractType==3">销售消耗</span>
                                </template>
                                </el-table-column>
                                  <el-table-column
                                    prop="deductionAmount"
                                    label="扣款金额（元）"
                                    mini-width="300"
                                >
                                </el-table-column>
                                </el-table>
                            </div>
                    </div>
                    <span>
                        {{
                            test
                        }}
                    </span>
                    <!-- 附件信息 -->
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp
                            :relationId="attachId"
                            bucketName="turnover"
                        />
                    </div>
                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                :billType="6082"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div class="buttons">
                <span class="tip"><span style="color: red; margin-right: 0">*</span>为必填项</span>

            <ComExaButtons :auditState="auditState" :state="basicForm.state" @exas="exas" :founderId="basicForm.founderId" />
            <el-button size="small" @click="handleClose">关闭</el-button>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    </div>
</template>

<script>
import AttachComp from '@/components/common/attachIndex'
import ComAuditHistoryIndex from '@/pages/revolveMaterialManage/components/auditHistory/auditHistoryIndex'
import auditRequest from '@/api/turnover/audit.js'
import { mapMutations, mapState } from 'vuex'
import otherRequest from '@/api/turnover/other.js'
import { setSelectQuantityAmortizations, setSelectAmountAmortizations, setTurnoverReceiveInventorySelectContract } from '@/api/turnover/ppw.js'
import ComExaButtons from '@/components/common/exaButtons'
import { exas, saveAll, submitCommit, deleteLogic, detailedTableDataComputed } from '@/pages/revolveMaterialManage/common/revolveCom.js'
import { getRmbRate,  } from '@/api/equip/common.js'
import { getUuid, openAppClient } from '@/utils/common'
// import { doChildren } from '@/api/turnover/utils.js'

import $ from 'jquery'
import '@/utils/jquery.scrollTo.min'
export default {
    components: {
        AttachComp,
        ComAuditHistoryIndex,
        ComExaButtons
    },
    computed: {
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billId
        },
        //获取状态
        statusLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.state
                const obj = state.find(x=>x.value == param)
                return obj.label
            }
        },
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            providTypeArr: state => state.contract.ctClassify.supplyTypeList, //甲供类型
            receiveBusinessType: state =>
                state.turnover.turnoverData.receiveBusinessType
        }),

        // 红单状态
        redBillStateFun () {
            let redState = ''
            switch (this.basicForm.redState) {
            case 0:
                redState = '冲销中'
                break
            case 1:
                redState = '冲销中'
                break
            case 2:
                redState = '已冲销'
                break
            case 3:
                redState = '红单'
                break
            }
            return redState
        },
        detailedTableDataComputed () {
            return detailedTableDataComputed(this.detailedTableData)
        },
        // 分包合同匹配：甲供、超甲供扣款、非加工扣款
        consumeTypeComputed () {
            return row => {
                if (row.planAmount <= 0) return '超甲供扣款'
                if(row.apportionmentAmount <= row.planAmount) return '甲供'
            }
        }
    },
    mounted () {
        this.getLastConHeight()
        // 保存所有tabName
        const arr = ['baseInfo', 'detailed', 'cost', 'attach', 'auditHistory']

        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    },
    created () {
        this.billId = this.$route.query.billid
        this.getBasicInfo()
        this.getCurrentUnitInfo()
        this.getDtlList()
        this.getCostSharingDtl()

        const { baseCyByOrgId } = this.userInfo
        this.basicForm.baseCurName = baseCyByOrgId.currencyName  //本位币
        this.basicForm.baseCurId = baseCyByOrgId.currency
    },
    data () {
        return {
            tabsName: 'baseInfo',
            row: {},
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            basicForm: {
                amortizationAmount: 0,
                amortizationDate: '',
                baseAmortizationAmount: 0,
                baseCurId: '',
                baseCurName: '',
                baseCurRate: 0,
                billId: '',
                billNo: '',
                currency: null,
                currencyId: null,
                inputId: '',
                inputName: '',
                isRed: 0,
                orgId: '',
                orgName: '',
                parentId: '',
                remarks: '',
                state: 0,
                workId: ''
            },
            query: {
                limit: 10,
                number: '',
                orgname: '',
                page: 1,
                states: []
            },
            formLabelWidth: '150px',
            detailedTableData: [], //物资明细
            changeTableData: [], //变更信息
            basicInfo: {},
            MouseEnterId: 0,
            showBaseCurName: true,
            errorList: [],
            errorMsg: [],

            auditState: {},
            auditParams: {
                billId: this.$route.query.billid,
                billType: 6082,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            },
            rules: {
                amortizationDate: [
                    {
                        required: true,
                        message: '请选择摊销日期',
                        trigger: 'chenge'
                    }
                ],
                currencyId: [
                    {
                        required: true,
                        message: '请选择币种',
                        trigger: 'blur'
                    }
                ],
                baseCurRate: [
                    {
                        required: true,
                        message: '请填写本位币汇率',
                        trigger: 'blur'
                    }
                ],
            },
            tabArr: [],
            costTableData: [],
            isBatch: [
                {
                    flag: false,
                    batch: '进入批量管理'
                },
                {
                    flag: false,
                    batch: '进入批量管理'
                }
            ],
            redBillStateStyle: {
                width: '300px',
                height: '30px',
                color: '#fff',
                backgroundColor: '#FF2300',
                'text-align': 'center'
            },
            isRedSingle: false,
            // providTypeArr: [
            //     {
            //         label: '工程消耗', value: '0'
            //     },
            //     {
            //         label: '安全环保支出', value: '1'
            //     },
            //     {
            //         label: '研发支出', value: '2'
            //     },
            // ],
            test: []
        }
    },
    methods: {
        ...mapMutations(['setAuditParams', 'setSelectedInfo']),
        batchOperation () {
            if(this.isBatch) {
                this.isBatch[0].batch = '退出批量管理'
                this.$refs.planTable.clearSelection()
            }else{
                this.isBatch[0].batch = '进入批量管理'
            }

        },
        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },

        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight =
                        document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        //币种切换
        currencyChange (val) {
            this.basicForm.currency = this.currencyForm.find(
                x => x.value === val
            ).label //币种
            if (this.basicForm.currency === '人民币') {
                this.basicForm.rmbRate = 1
            } else {
                getRmbRate({
                    //获取机构下某币种的人民币汇率
                    currency: val,
                    orgId: this.userInfo.orgInfo.orgId
                })
                    .then(res => {
                        this.basicForm.rmbRate = res.rate
                    })
                    .catch(() => {})
            }
            if (this.basicForm.currencyId === this.basicForm.baseCurId) {
                //币种=本位币
                this.basicForm.baseCurRate = 1
                this.showBaseCurName = false
            } else {
                this.basicForm.baseCurRate = null
                this.showBaseCurName = true
            }
        },
        //编辑
        checkLogEdit () {
            if(this.checkLog.length > 1) {
                this.clientPop('err', '一次只能选择一条数据！')
            }else{
                this.setAuditParams({ id: this.checkLog[0].id })
                openAppClient(`/outAccountCheckLogAdd?billid=${this.billid}&isNewAdd=false`, '外协台账检查记录编辑', ()=>{
                    this.getCheckLog()
                },
                null, ()=>{
                    this.getCheckLog()
                })
            }
        },

        //删除
        handleTurnoverDelete (row) {
            this.clientPop('info', ' 确定要删除吗？数据删除后不可恢复，请谨慎操作。', ()=>{
                row.changeType = -1
                // this.$set(this.turnoverLogList[$index], 'changeType', -1)
                // this.turnoverLogListCopy.splice($index, 1)
            })
        },
        getBasicInfo () {
            this.$Ajax
                .httpGet({
                    url: '/turnover/amortization/findById',
                    params: {
                        billId: this.billId
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    res.redState === 3 ? this.isRedSingle = true : this.isRedSingle = false
                    for (let key in res) {
                        this.basicForm[key] = res[key]
                    }
                })
        },
        getCurrentUnitInfo () {
            auditRequest.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        //更新基本信息
        updateBaseInfo () {
            this.basicForm.isSignContract ? this.basicForm.isSignContract = 1 : this.basicForm.isSignContract = 0
            return new Promise((resolve, reject)=>{

                this.$refs.ruleForm.validate(valid => {
                    if (valid) {
                        otherRequest.turnoverAmortizationUpdate(this.basicForm).then(()=>{
                            this.getBasicInfo() //更新基本信息
                            resolve()
                        }).catch(err=>{
                            this.setError('baseInfo')
                            reject(err)
                        })
                    }
                    else {

                        this.setError('baseInfo')
                        this.scorllError()
                        reject()
                    }
                })
            })
        },
        getDtlList () {
            otherRequest.turnoverAmortizationGetDtlList(this.billId).then(res=>{
                if (res.length > 0) {
                    res.forEach(item => {
                        item.materialClassName = item.topClassName
                        item.uuid = getUuid()
                        item.businessType = this.basicForm.businessTypeKey

                        item.children.forEach(i => {
                            i.parentId = item.uuid
                            i.uuid = i.dtlId
                            i.changeType = 0
                        })

                        const count = item.children.reduce(
                            (prev, c) => (prev += c.amount || 0),
                            0
                        )
                        item.materialName = `小计： ${count}`
                    })

                    this.detailedTableData = res
                    // this.collectCount()
                }
            })
        },
        getCostSharingDtl () {
            otherRequest.turnoverAmortizationGetCostSharingDtl(this.billId).then(res => {
                this.costTableData =  res.map(v => {
                    v.providType = Number(v.providType)
                    return v
                })
            })
        },
        //更新计划明细
        updateBudgetDtl () {
            return new Promise((resolve, reject)=>{

                otherRequest.turnoverAmortizationUpdateDtl(this.detailedTableData).then(()=>{
                    this.getDtlList() //更新明细
                    resolve()
                }).catch(err=>{
                    this.setError('detailed')
                    reject(err)
                })
                // this.verifyTable().then(()=>{
                //     otherRequest.turnoverAmortizationUpdateDtl(this.detailedTableData).then(()=>{
                //         this.getDtlList() //更新明细
                //         resolve()
                //     }).catch(err=>{
                //         this.setError('detailed')
                //         reject(err)
                //     })
                // }).catch(err=>{
                //     this.setError('detailed')
                //     reject(err)
                // })
            })
        },
        // 更新分包商陶晓成本明细
        updateCostSharingDtl () {
            return new Promise((resolve, reject)=>{
                otherRequest.turnoverAmortizationUpdateCostSharingDtl(this.costTableData).then(()=>{
                    this.getCostSharingDtl() //更新明细
                    resolve()
                }).catch(err=>{
                    this.setError('detailed')
                    reject(err)
                })
            })
        },
        //点击删除弹窗
        deletePlanList () {
            const length = this.planSelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else{
                this.clientPop(
                    'info',
                    `已选择【${length}】条数据，确定要删除吗？数据删除后不可恢复，请谨慎操作！`,
                    this.delete
                )
            }

        },

        async exas (arg) {
            const requestFn = () => {
                return []
            }
            exas(arg, this, requestFn)
        },
        //保存全部数据
        saveAll () {
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                    this.updateBudgetDtl(),
                    this.updateCostSharingDtl(),

                ]
            }
            saveAll(this, requestFn)
        },
        submitCommit () {
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                    this.updateBudgetDtl(),
                    this.updateCostSharingDtl(),

                ]
            }
            submitCommit(this, requestFn)
        },

        //刷新历史审核列表
        getAuditHistory () {
            this.$refs.AuditHistoryRef.auditHistory()
        },
        //点击删除
        clickDel () {
            this.clientPop(
                'info',
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                this.delData
            )
        },
        delData () {
            this.$Ajax
                .httpGet({
                    url: '/turnover/amortization/delete',
                    params: { billId: this.billId },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(() => {
                    this.clientPop('suc', '删除成功', this.handleClose)
                })
        },
        handleClose () {
            this.$router.push('/revolveAmortizeList')
        },
        /**
         * 物资逻辑
         */
        // 按金额
        clickMoneySource () {
            setSelectAmountAmortizations(this.detailedTableData, this.billId).then(res=>{
                this.detailedTableData = res
                this.detailedTableData[0].children.forEach(v => {
                    this.curStateChange(v)
                })
                this.collectCount()
            })
        },
        // 按数量
        async clickNumSource () {
            setSelectQuantityAmortizations(this.detailedTableData, this.billId).then(res => {
                this.test = res
                this.detailedTableData = res

            })
            openAppClient
        },
        // 选择分包商
        amortizationReturnSelectContract () {
            if(this.detailedTableData.length == 0) return this.clientPop('err', '请添加明细')
            setTurnoverReceiveInventorySelectContract(this.costTableData, this.billId).then(res=>{
                this.costTableData = res
                this.test = this.costTableData
                this.setSelectedInfo(res)
            })
        },
        //判断当前状态是否已修改
        curStateChange (row) {
            this.curRow = row
            if (row.changeType !== 1) {
                {
                    this.curRow.changeType = 2
                }
            }
            // 计算截止本期末摊销数量
            if (row.quantity) {
                row.currTotalAmortizationQuantity =
                     Number(row.currAmortizationQuantity) + Number(row. prevTotalAmortizationQuantity)
                this.collectCount()
            }
            // 计算截止本期末摊销金额
            if(row.amount && row.currAmortizationAmount) {
                row.currTotalAmortizationAmount = Number(row.currAmortizationAmount) + Number(row. prevTotalAmortizationAmount)
                this.collectCount()
            }

            // 选择分包商  扣款金额 = 分摊金额-设计金额
            if (row.apportionmentAmount && row.planAmount) {
                let count = (Number(row.apportionmentAmount) - Number(row.planAmount)  ).toFixed(4)
                row.deductionAmount = count > 0 ? count : 0
            }
            // 分包商分摊比例
            if(row.apportionmentAmount && this.basicForm.amortizationAmount !== 0) {
                row.apportionmentRatio = Number(row.apportionmentAmount / this.basicForm.amortizationAmount).toFixed(4)
            }

        },
        //明细金额向上汇总到基础表单 不含税计划金额（元）
        collectCount () {
            this.basicForm.amortizationAmount = 0
            this.basicForm.amortizationQuantity = 0
            this.detailedTableData.forEach(v => {
                v.children.forEach(item => {
                    if (v.changeType != -1) {

                        // 金额
                        if(item.currTotalAmortizationAmount && item.amortizationType === 0) {
                            this.basicForm.amortizationAmount += Number(item.currAmortizationAmount)
                        }
                        // 数量
                        if(item.currTotalAmortizationQuantity && (item.amortizationType === 1 || item.amortizationType === 2)) {
                            this.basicForm.amortizationQuantity += Number(item.currAmortizationQuantity)
                        }

                    }

                })

                const count = v.children.reduce(
                    (prev, c) => (prev += c.currTotalAmortizationAmount || 0),
                    0
                )
                v.materialName = `小计： ${count}`
            })
        },
        //点击删除的时候
        deleteEle (row, $index) {
            this.clientPop(
                'info',
                this.oneDeleteErr,
                () => {
                    deleteLogic(row, $index, this, ['amortizationAmount', 'amortizationQuantity'])
                }
            )
        },
        //计划明细非空验证
        verifyTable () {
            return new Promise((resolve, reject)=>{

                this.errorMsg = []
                if(this.detailedTableData.length > 0) {
                    this.detailedTableData.forEach(v => {
                        v.children.forEach((item, index) => {
                            if (item.changeType !== -1) {
                            // if (item.texture == '' || item.texture == null) {
                            //     let str = `请填写第 ${index + 1} 行的材质`
                            //     this.errorMsg.push(str)
                            // }
                                if (item.quantity == '' || item.quantity == null) {
                                    let str = `请填写第 ${index + 1} 行的需求数量`
                                    this.errorMsg.push(str)
                                }
                                if (item.price == '' || item.price == null) {
                                    let str = `请填写第 ${index + 1} 行的租赁单价（元）`
                                    this.errorMsg.push(str)
                                }
                                if (item.degree == '' || item.degree == null) {
                                    let str = `请填写第 ${index + 1} 行的单价`
                                    this.errorMsg.push(str)
                                }
                                if (item.timeUnit == '' || item.timeUnit == null) {
                                    let str = `请填写第 ${index + 1} 行的计时单位`
                                    this.errorMsg.push(str)
                                }
                                if (item.useTime == '' || item.useTime == null) {
                                    let str = `请填写第 ${index + 1} 行的预计使用时间`
                                    this.errorMsg.push(str)
                                }
                                if (item.cost == '' || item.cost == null) {
                                    let str = `请填写第 ${index + 1} 行的预计进场费用`
                                    this.errorMsg.push(str)
                                }

                            }
                        })
                    })
                }

                if (this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()

                } else {
                    this.isErrorMsg = false
                    resolve()

                }

            })

        },
        // 处理树
        tableRowClassName ({ row }) {
            if (row.children) {
                return 'warning-row'
            }else if(row.changeType === -1) {
                return  'row-hide'
            }else{
                return  'row-show'
            }
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
    }
}
</script>

<style lang="scss" scoped>
.e-table {
    min-height: auto;
    background: #fff;
}
.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}

::v-deep.el-input--suffix .el-input__inner {
    padding-right: 5px;
}
::v-deep.el-table .cell {
    text-align: center;
}
#iconEdit:hover {
    color: red;
}

.like {
    color: rgb(46, 97, 215);
    font-size: 17px;
    line-height: 30px;
    cursor: pointer;
}
.detailed-total{
    padding: 20px 0;
    display: flex;
    justify-content: space-between;
    .detailed-left{
        display: flex;
        .sub-total{
            margin-left: 20px;

        }
    }
}
</style>
